#!/usr/bin/python
from struct import pack
from struct import unpack
from struct import calcsize
from StructException import InvalidStringError

"""User Struct - Defines basic fields and methods pertinent to a user.
	TODO: User struct testing."""

class UserStruct:
	"""UserStruct defines a user:
		name - user name,
		id - User id. """
	def __init__(T, name, uid):
		"""Initialize user:
			name(user) - user name,
			id(uid) - user id."""
		T.user = name
		T.id = uid
	def get_user(T):
		"""Return user name."""
		return T.user
	def get_id(T):
		"""Return user ID."""
		return T.id

#static variables
#int id,name_size
#str user
int_fmt="2i"
str_fmt="%is"
int_fmt_size=calcsize(int_fmt)
format=int_fmt+str_fmt

#static functions
def store(obj):
	"""Create a bitstring coresponding to object."""
	if not obj:
		raise ValueError("NullPonterException: No UserStruct object found.")
	name = obj.get_user
	str_size = len(name)
	fmt = format%(str_size,)
	return pack(fmt, obj.get_id, str_size, name)
def create(bytes):
	"""Create a UserStruct from bitstring."""
	if len(bytes)<int_fmt_size:
		raise InvalidStringError("Error creating UserStruct - int_fmt size does not match actual size. Format Size: %i"%int_fmt_size, bytes)
	#unpack ints
	(uid, str_size) = unpack(int_fmt, bytes[:int_fmt_size])
	fmt_size = calcsize(format%str_size)
	if len(bytes)<fmt_size:
		raise InvalidStringError("UserStruct - Format size does not match actual size. Format Size: %i"%fmt_size, bytes)
	#unpack strs
	tmp_fmt = str_fmt % (str_size,)
	(name,) = unpack(tmp_fmt, bytes[int_fmt_size:])
	obj=UserStruct(name, uid)
	return obj
